package cn.itcast.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.AreaDao;
import cn.itcast.bos.dao.base.CourierDao;
import cn.itcast.bos.dao.base.FixedAreaDao;
import cn.itcast.bos.dao.take_delivery.OrderDao;
import cn.itcast.bos.dao.take_delivery.WorkBillDao;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.take_delivery.OrderService;
import cn.itcast.bos.utils.AliSMSUtil;
import cn.itcast.crm.service.CustomerService;


@Service("orderService")
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderDao orderDao;
	
	@Autowired
	private AreaDao areaDao;
	
	@Autowired
	private CustomerService customerProxy;
	
	@Autowired
	private FixedAreaDao fixedAreaDao;
	
	@Autowired
	private WorkBillDao workBillDao;
	
	/**
	  * @Description: 1、保存订单数据 2、根据寄件人信息尝试自动分单
	*/
	public void save(Order order) {
		order.setOrderNum(UUID.randomUUID().toString());
		order.setOrderTime(new Date());
		//问题：在前台系统提交区域对象是瞬时态(因为区域对象是new出来的,没有id)
		//解决：方式一：根据省市区查询一条区域记录--持久态区域对象
		//方式二：将订单实体中区域对象改为null  order.setSendArea(null);
		
		Area sendArea = order.getSendArea();
		sendArea=areaDao.findByProvinceAndCityAndDistrict(sendArea.getProvince(),sendArea.getCity(),sendArea.getDistrict());
		order.setSendArea(sendArea);
		
		Area recArea = order.getRecArea();
		recArea=areaDao.findByProvinceAndCityAndDistrict(recArea.getProvince(),recArea.getCity(),recArea.getDistrict());
		order.setRecArea(recArea);
		
		//持久态关联瞬时态无法向数据库存数据,将瞬时态变为持久态就可以向数据库存数据
		orderDao.save(order);
		
		//尝试自动分单
		//调用CRM根据地址查询定区ID
		String fixedAreaId = customerProxy.findFixedAreaIdByAddress(order.getSendAddress());
		if(StringUtils.isNotBlank(fixedAreaId)){
			//根据定区ID查询定区对象
			FixedArea fixedArea = fixedAreaDao.findOne(fixedAreaId);
			//定区-快递员：多对多
			Set<Courier> couriers = fixedArea.getCouriers();
			//根据订单时间判断快递员是否上班时间；根据快递员取件任务数量
			for (Courier courier : couriers) {
				//找到该定区负责快递员
				WorkBill workBill = new WorkBill();
				workBill.setAttachbilltimes(0);//追单次数
				workBill.setBuildtime(new Date());
				workBill.setCourier(courier);//工单关联快递员
				workBill.setPickstate("待取件");
				workBill.setOrder(order);//工单关联订单
				workBill.setRemark(order.getRemark());
				workBill.setType("新单");
				workBillDao.save(workBill);
				Map<String, Object> templateParam = new HashMap<>();
				templateParam.put("customerAddress", order.getSendAddress());
				templateParam.put("customerName", order.getSendName());
				templateParam.put("customerTelephone", order.getRecMobile());
				templateParam.put("customerRemark", order.getSendMobileMsg());
				//发送短信通知快递员上门取件
				Boolean flag = AliSMSUtil.sendMessge(courier.getTelephone(), "SMS_133150274", templateParam );
				workBill.setSmsNumber(flag.toString());
				
				//完成自动分单
				order.setOrderType("自动分单");
				order.setCourier(courier);//订单关联快递员
				return;
			}
		}
		
		
		
		/*
		 * 北京市海淀区建材城西路金燕龙办公楼一层    北京市北京市海淀区
		 * 
		 */
		//策略二
		//通过寄件人省市区查询该区域下分区记录	
		Set<SubArea> subareas = sendArea.getSubareas();
		//获取寄件人详细地址--确定地址属于哪个分区
		String sendAddress = order.getSendAddress();
		for (SubArea subArea : subareas) {
			if(sendAddress.contains(subArea.getKeyWords())||sendAddress.contains(subArea.getAssistKeyWords())){
				//确定分区属于哪个定区
				FixedArea fixedArea = subArea.getFixedArea();
				//定区-快递员：多对多
				Set<Courier> couriers = fixedArea.getCouriers();
				//根据订单时间判断快递员是否上班时间；根据快递员取件任务数量
				for (Courier courier : couriers) {
					//找到该定区负责快递员
					WorkBill workBill = new WorkBill();
					workBill.setAttachbilltimes(0);
					workBill.setBuildtime(new Date());
					workBill.setCourier(courier);//工单关联快递员
					workBill.setPickstate("待取件");
					workBill.setOrder(order);//工单关联订单
					workBill.setRemark(order.getRemark());
					workBill.setType("新单");
					workBillDao.save(workBill); //保存工单记录
					Map<String, Object> templateParam = new HashMap<>();
					templateParam.put("customerAddress", order.getSendAddress());
					templateParam.put("customerName", order.getSendName());
					templateParam.put("customerTelephone", order.getRecMobile());
					templateParam.put("customerRemark", order.getSendMobileMsg());
					//发送短信通知快递员上门取件
					Boolean flag = AliSMSUtil.sendMessge(courier.getTelephone(), "SMS_133150274", templateParam );
					workBill.setSmsNumber(flag.toString());
					
					//完成自动分单
					order.setOrderType("自动分单");
					order.setCourier(courier);  //订单关联快递员
					return;
				}
				
			}
		}
		
		
		//该订单分单类型改为人工分单
		order.setOrderType("人工分单");
	}

	@Override
	public List<Order> findOrderByCourierId() {
		return  orderDao.findByCourierIsNull();
	}
	@Autowired 
	private CourierDao courierDao;
	@Override
	public void updateOrderById(String sendAddress, Integer courierid, Integer oid) {
	orderDao.updateOrderById(sendAddress,courierid,oid);
	WorkBill workBill = new WorkBill();
	workBill.setAttachbilltimes(0);//追单次数
	workBill.setBuildtime(new Date());
	Courier courier = courierDao.findOne(courierid);
	workBill.setCourier(courier);//工单关联快递员
	workBill.setPickstate("待取件");
	Order order = orderDao.findOne(oid);
	workBill.setOrder(order);//工单关联订单
	workBill.setRemark(order.getRemark());
	workBill.setType("新单");
	workBillDao.save(workBill);
	Map<String, Object> templateParam = new HashMap<>();
	/*templateParam.put("customerAddress", order.getSendAddress());
	templateParam.put("customerName", order.getSendName());
	templateParam.put("customerTelephone", order.getRecMobile());
	templateParam.put("customerRemark", order.getSendMobileMsg());*/
	templateParam.put("username", courier.getName());
	//发送短信通知快递员上门取件
	Boolean flag = AliSMSUtil.sendMessge(courier.getTelephone(), "SMS_133276084", templateParam );
	workBill.setSmsNumber(flag.toString());
	}

}
